package com.nefu.softlab.xjwc.service.impl;

import com.nefu.softlab.xjwc.common.Constant;
import com.nefu.softlab.xjwc.mapper.*;
import com.nefu.softlab.xjwc.model.Activity;
import com.nefu.softlab.xjwc.model.Classify;
import com.nefu.softlab.xjwc.model.User;
import com.nefu.softlab.xjwc.model.vo.ActivityVo;
import com.nefu.softlab.xjwc.service.ActivityService;
import com.nefu.softlab.xjwc.service.DocumentService;
import com.nefu.softlab.xjwc.service.ProjectService;
import com.nefu.softlab.xjwc.service.ScoreService;
import com.nefu.softlab.xjwc.utils.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import static com.nefu.softlab.xjwc.common.Constant.UPLOAD_PATH_PREFIX;

import java.io.File;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author LiXiwen
 * @date 2020/2/7 19:04
 */
@Service
public class ActivityServiceImpl implements ActivityService {

    private final ActivityMapper activityMapper;
    private final UserMapper userMapper;
    private final LoggerUtil logger;
    private final RedisMapper redisMapper;
    private final DocumentService documentService;
    private final ProjectService projectService;
    private final ScoreService scoreService;

    @Autowired
    public ActivityServiceImpl(ActivityMapper activityMapper, UserMapper userMapper, LoggerUtil logger, RedisMapper redisMapper, DocumentService documentService, ProjectService projectService, ScoreService scoreService) {
        this.activityMapper = activityMapper;
        this.userMapper = userMapper;
        this.logger = logger;
        this.redisMapper = redisMapper;
        this.documentService = documentService;
        this.projectService = projectService;
        this.scoreService = scoreService;
    }

    @Override
    public JSONResult addActivity(ActivityVo activity) throws XJWCException {
//        if (null != activity.getStartTime()) {
//            activity.setStartTime(TimeUtil.getTime(activity.getStartTime()));
//        }
//        if (null != activity.getEndTime()) {
//            activity.setEndTime(TimeUtil.getTime(activity.getEndTime()));
//        }

        List<Classify> tags = activity.getTag();
        int sum = 0;
        for (Classify classify : tags) {
            sum += (int)(classify.getPart() * 100);
        }
        if (sum != 100) {
            throw new XJWCException("设置权重有误！");
        }

        List<String> users = activity.getList();

        List<Map<String, Object>> userList = new ArrayList<>();

        for (String id : users) {
            Map<String, Object> map = new HashMap<>();
            User u = userMapper.selectUserInfoOne(id);
            map.put("userId", id);
            map.put("phone", u.getPhone());
            map.put("userName", u.getUserName());
            map.put("unit", u.getUnit());
            map.put("role", u.getRole());
            map.put("activity", u.getActivity());
            userList.add(map);
        }

        if (!activityMapper.addActivity(activity)) {
            throw new XJWCException("新建活动失败，请重新尝试!");
        }

        // 只要建立活动，就生成一个文件夹 = 自增id + "-" + 活动名，避免了活动名称相同。数据库存的依然是活动名。
        String dir = activity.getActivityId() + "-" + activity.getName();

        System.out.print("ActivityServiceImpl ---> addActivity , mkdir ---> activityDir : " + dir);

        FileUtil.mkdir(dir);

        redisMapper.set(activity.getActivityId().toString(), userList);
        redisMapper.set(Constant.TAG_ACTIVITY + activity.getActivityId().toString(), activity.getTag());

        return JSONResult.ok("新建活动成功");
    }

    @Override
    public JSONResult selectAllActivity(Activity activity) throws XJWCException {
        List<Activity> rtv = activityMapper.selectAllActivity(activity);
        if (null == rtv || 0 >= rtv.size()) {
            throw new XJWCException("没有该条件下的活动，请重新尝试!");
        }
        return JSONResult.ok(rtv);
    }

    @Override
    public JSONResult updateActivity(ActivityVo activity) throws XJWCException {
        Activity tmp = new Activity();
        tmp.setActivityId(activity.getActivityId());
        String oldName = activityMapper.selectAllActivity(tmp).get(0).getName();

//        if (null != activity.getStartTime()) {
//            activity.setStartTime(TimeUtil.getTime(activity.getStartTime()));
//        }
//        if (null != activity.getEndTime()) {
//            activity.setEndTime(TimeUtil.getTime(activity.getEndTime()));
//        }


        // 更新活动
        if (!activityMapper.updateActivity(activity)) {
            throw new XJWCException("更新活动失败，请重新尝试!");
        }

        scoreService.deleteScoreByActivityId(activity.getActivityId());

        // 如果活动名为null或空字符串，不更新
        if (!StringUtils.isEmpty(activity.getName())) {
            String oldDir = activity.getActivityId() + "-" + oldName;
            String newDir = activity.getActivityId() + "-" + activity.getName();

            System.out.println("ActivityServiceImpl.updateActivity() ---> update activityDir --> oldDir : " + oldDir + " , newDir : " + newDir);

            // 更新活动文件夹名字
            FileUtil.updateDir(oldDir, newDir);

            if (!oldDir.equals(newDir)) {
                if (!documentService.updateDocName(oldDir, newDir, activity.getActivityId())) {
                    throw new XJWCException("更新文件存储路径失败，请重新更新活动!");
                }
            }
        }


        if (activity.getList() != null) {
            List<String> users = activity.getList();

            List<Map<String, Object>> userList = new ArrayList<>();

            for (String id : users) {
                Map<String, Object> map = new HashMap<>();
                User u = userMapper.selectUserInfoOne(id);
                map.put("userId", id);
                map.put("phone", u.getPhone());
                map.put("userName", u.getUserName());
                map.put("unit", u.getUnit());
                map.put("role", u.getRole());
                map.put("activity", u.getActivity());
                userList.add(map);
            }
            redisMapper.set(activity.getActivityId().toString(), userList);
        }

        if (activity.getTag() != null) {
            redisMapper.set(Constant.TAG_ACTIVITY + activity.getActivityId().toString(), activity.getTag());
        }

        return JSONResult.ok("更新活动成功");
    }

    @Override
    public JSONResult deleteActivity(Integer activityId) throws XJWCException {
        Activity activity = new Activity();
        activity.setActivityId(activityId);

        // 添加了斜杠
        String dirPath = UPLOAD_PATH_PREFIX + activityId + "-" + activityMapper.selectAllActivity(activity).get(0).getName() + "/";

        // 需要把 document表，项目表 下面的也给删了，但是删不删无所谓了，反正查不到，还是删吧。
        documentService.deleteDocumentsByActivityId(activityId);
        projectService.deleteProjectsByActivityId(activityId);
        scoreService.deleteScoreByActivityId(activityId);

        if (!activityMapper.deleteActivity(activity)) {
            throw new XJWCException("删除活动失败，请重新尝试!");
        }

        System.out.println("delete activity's dir, dirPath : " + dirPath);

        // 删除文件夹。
        FileUtil.delAllFile(new File(dirPath));

        return JSONResult.ok("删除活动成功");
    }

    @Override
    public JSONResult selectInTimeActivity(String userId) throws XJWCException {
        List<Activity> rtv = activityMapper.selectAllActivity(new ActivityVo());
        List<Map<String, Object>> al = new ArrayList<>();
        for (Activity act : rtv) {
            if (redisMapper.hasKey(act.getActivityId().toString())) {
                List<Map<String, Object>> list = (List<Map<String, Object>>) redisMapper.get(act.getActivityId().toString());
                for (Map<String, Object> m : list) {
                    if (userId.equals(m.get("userId")) && TimeUtil.isTime(act)) {
                        Map<String, Object> map = new HashMap<>();
                        map.put("activityId", act.getActivityId());
                        map.put("name", act.getName());
                        map.put("info", act.getInfo());
                        map.put("startTime", act.getStartTime());
                        map.put("endTime", act.getEndTime());
                        map.put("unit", act.getUnit());
                        map.put("type", act.getType());
                        al.add(map);
                        break;
                    }
                }
            }
        }
        if (0 >= al.size()) {
            throw new XJWCException("没有该条件下的活动，请重新尝试!");
        }
        return JSONResult.ok(al);
    }

    @Override
    public JSONResult selectActivityDetail(Activity activity) throws XJWCException {
        List<Activity> list = activityMapper.selectAllActivity(activity);
        Map<String, Object> map = new HashMap<>();
        if (null != list && list.size() == 1) {
            Activity p = list.get(0);
            map.put("activityId", p.getActivityId());
            map.put("startTime", p.getStartTime());
            map.put("name", p.getName());
            map.put("unit", p.getUnit());
            map.put("endTime", p.getEndTime());
            map.put("info", p.getInfo());
            if (redisMapper.hasKey(Constant.TAG_ACTIVITY + p.getActivityId().toString())) {
                map.put("tag", redisMapper.get(Constant.TAG_ACTIVITY + p.getActivityId().toString()));
            } else {
                map.put("tag", "");
            }
            if (redisMapper.hasKey(p.getActivityId().toString())) {
                map.put("list", redisMapper.get(p.getActivityId().toString()));
            } else {
                map.put("list", "");
            }
            map.put("type", p.getType());
        } else {
            throw new XJWCException("查询项目出现异常，请重新尝试!");
        }
        return JSONResult.ok(map);
    }

    @Override
    public JSONResult getAllActivity() throws XJWCException {
        List<Activity> list = activityMapper.selectAllActivity(new Activity());
        System.out.println(list.size());
        List<Map<String, Object>> al = new ArrayList<>();
        if (list != null) {
            for (Activity act : list) {
                Map<String, Object> map1 = new HashMap<>();
                map1.put("activityId", act.getActivityId());
                map1.put("startTime", act.getStartTime());
                map1.put("name", act.getName());
                map1.put("unit", act.getUnit());
                map1.put("endTime", act.getEndTime());
                map1.put("info", act.getInfo());
                map1.put("type", act.getType());

                if (redisMapper.hasKey(Constant.TAG_ACTIVITY + act.getActivityId().toString())) {
                    map1.put("tag", redisMapper.get(Constant.TAG_ACTIVITY + act.getActivityId().toString()));
                } else {
                    map1.put("tag", "");
                }
                if (redisMapper.hasKey(act.getActivityId().toString())) {
                    map1.put("list", redisMapper.get(act.getActivityId().toString()));
                } else {
                    map1.put("list", "");
                }
                al.add(map1);
            }
        } else {
            throw new XJWCException("查询活动失败，请重新尝试!");
        }

        return JSONResult.ok(al);
    }


}
